package database

import (
	"errors"
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/micro/go-micro/util/log"
	"github.com/pku-hit/dict/model/entity"
	"github.com/pku-hit/dict/proto"
	"github.com/pku-hit/dict/util"
	"time"
)

func NewaddressDict(category, parentId, code, name, pyCode string, dictType proto.AddressDictType, value interface{}) (dict *entity.DictInfo, err error) {

	if dict, err = ExistDictWithCode(code); err == nil && dict != nil {
		log.Warnf("exist dict: %s", util.Json.ToJsonString(dict))
		fmt.Println("存在该数据！code不能重复！")
		return
	}
	now := time.Now()
	dict = &entity.DictInfo{
		ID:       util.Snowflake.GenId(),
		Code:     code,
		Name:     name,
		PyCode:   pyCode,
		Value:    util.Json.ToJsonString(value),
		Status:   proto.DictStatus_Normal.String(),
		CreateAt: &now,
		UpdateAt: &now,
	}

	if util.String.IsEmptyString(parentId) {
		err = errors.New("没有指定ParentId的字典")
		return
	} else {
		if dictType == proto.AddressDictType_country {
			dict.Type = proto.AddressDictType_country.String()
		} else if dictType == proto.AddressDictType_province {
			dict.Type = proto.AddressDictType_province.String()
		} else if dictType == proto.AddressDictType_city {
			dict.Type = proto.AddressDictType_city.String()
		} else if dictType == proto.AddressDictType_area {
			dict.Type = proto.AddressDictType_area.String()
		} else if dictType == proto.AddressDictType_street{
			dict.Type = proto.AddressDictType_street.String()
		} else {
			dict.Type = ""
		}
		dict.ParentId = parentId
		dict.Type = dictType.String()
	}
	dict.Category = "address"
	err = db.Save(dict).Error
	//db.s
	if err != nil {
		log.Error("save new dict error %s.", err.Error())
	}
	return
}

//根据code删除数据

func DeleteAddressDict(code string, soft bool) (err error) {
	dict, err := ExistDictWithCode(code)
	if err == gorm.ErrRecordNotFound {
		return
	}
	now := time.Now()
	if soft {
		dict.Status = proto.DictStatus_Deleted.String()
		dict.DeleteAt = &now
		log.Info(util.Json.StructToMap(dict))
		err = db.Model(dict).Select("status", "delete_at").Update(util.Json.StructToMap(dict)).Error
	} else {
		err = db.Where("code = ?", code).Delete(new(entity.DictInfo)).Error
	}
	return
}

